package com.ponxu.mb.web;

import java.util.List;

import com.ponxu.mb.model.Category;
import com.ponxu.mb.model.Comment;
import com.ponxu.mb.model.Link;
import com.ponxu.mb.model.PageInfo;
import com.ponxu.mb.model.Post;
import com.ponxu.mb.service.CategoryService;
import com.ponxu.mb.service.CommentService;
import com.ponxu.mb.service.LinkService;
import com.ponxu.mb.service.OptionService;
import com.ponxu.mb.service.PostService;

/**
 * 提供FreeMarker调用方法, 方便主题制作
 * 
 * @author xwz
 */
public class BlogObject {
	private static BlogObject instance = new BlogObject();

	public static BlogObject getInstance() {
		return instance;
	}

	private BlogObject() {
	}

	/**
	 * 所有分类
	 * 
	 * @return
	 */
	public List<Category> getCategories() {
		return CategoryService.searchAllCategory();
	}

	/**
	 * 所有标签
	 * 
	 * @return
	 */
	public List<Category> getTags() {
		return CategoryService.searchAllTag();
	}

	/**
	 * 获取最近文章
	 * 
	 * @return
	 */
	public List<Post> getLatestPosts(int row) {
		PageInfo page = new PageInfo(1);
		page.setPageSize(row);
		return PostService.searchPublicPosts(page);
	}

	/**
	 * 查询某类别文章(方便制作CMS)
	 * 
	 * @param categoryId
	 * @param rows
	 * @return
	 */
	public List<Post> getPosts(int categoryId, int row) {
		PageInfo page = new PageInfo(1);
		page.setPageSize(row);
		return PostService.searchPublicPostsByCategoryId(categoryId, page);
	}

	/**
	 * 随机文章
	 * 
	 * @param row
	 * @return
	 */
	public List<Post> getRandomPosts(int row) {
		return PostService.searchRandomPosts(row);
	}

	/**
	 * 所有页面
	 * 
	 * @return
	 */
	public List<Post> getPages() {
		return PostService.searchAllPages();
	}

	/**
	 * 获取最近评论
	 * 
	 * @return
	 */
	public List<Comment> getLatestComments(int row) {
		PageInfo page = new PageInfo(1);
		page.setPageSize(row);
		return CommentService.searchComments(page, null);
	}

	/**
	 * 获取option配置
	 * 
	 * @param name
	 * @return
	 */
	public String getOption(String name) {
		return OptionService.read(name);
	}

	/**
	 * 友情链接
	 * 
	 * @return
	 */
	public List<Link> getLinks() {
		return LinkService.searchVisible();
	}

	/**
	 * 生成URL
	 * 
	 * @param obj
	 * @return
	 */
	public String getURL(Object obj) {
		StringBuilder url = new StringBuilder();
		if (obj instanceof Post) {
			Post post = (Post) obj;
			url.append("/post/").append(post.getId()).append("/")
					.append(post.getTitle()).append(".html");

		} else if (obj instanceof Category) {
			Category cat = (Category) obj;
			url.append("/category/").append(cat.getId()).append("/")
					.append(cat.getName());
		} else if (obj instanceof Link) {
			url.append(((Link) obj).getUrl());
		}
		return url.toString();
	}
}
